package com.project.hf.controller;

import com.project.hf.service.data;
import com.project.hf.utils.DirUtils;
import org.omg.CORBA.MARSHAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.nio.file.Path;
import java.nio.file.Paths;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
@RequestMapping("/apiv1")
@SpringBootApplication
public class HFTestController {

    // 日志
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(HFTestController.class);


    @PostMapping(path = "data1Json")
    public Map<String, String> data1Json(@RequestBody Map<String, String> args) {
        log.info("this is data1Json");

//        System.out.println(Sam.getSamUtil().getName());
        Map<String, String> map = new HashMap<String, String>();
//        map.put("name", "张三");
        map.put("age", "28");
        map.put("name", args.get("name"));
        return map;
    }

    @RequestMapping(value = "data2", method = RequestMethod.POST)
    public List data2(@RequestBody String s) {
        Map<String, String> map = new HashMap<String, String>();
//        map.put("name", "张三");

//        System.out.println(RequestBody);
        JSONObject json = JSONObject.parseObject(s);
        System.out.println(json);
        System.out.println(json.getString("Name"));
        data d = new data();

        List m = d.data1();
//        m.put("Name", json.getString("Name"));
        return m;
//        map.put("age", "28");
////        map.put("string", u.toString());
//        return map;
    }

    @RequestMapping(value = "dataForm", method = RequestMethod.POST)
    public Map<String, String> dataForm(@RequestParam("name") String name, @RequestParam("age") int age) {
        Map<String, String> map = new HashMap<String, String>();
//        map.put("name", "张三");
        map.put("age", String.valueOf(age));
        map.put("name", name);
        return map;
    }

    // todo 推荐使用

    @ResponseBody
    @RequestMapping(value = "/dataReact1", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String dataReact1(@RequestBody JSONObject jsonParam) {
        log.info("=========this is logging test, {}", "Spring Boot");

        // 直接将json信息打印出来
        System.out.printf("Recv args %s\n",jsonParam.toJSONString());

        // 将获取的json数据封装一层，然后在给返回
        JSONObject result = new JSONObject();
        JSONObject resultsub = new JSONObject();

        data mysqldata = new data();
        log.info("response:{}",mysqldata.data1());
        resultsub.put("dbData", mysqldata.data1());
        resultsub.put("requestArgs", jsonParam);

        // 返回String
        result.put("msg", "ok");
        result.put("method", "@ResponseBody");
        result.put("data", resultsub);

        return result.toJSONString();
    }


    @RequestMapping(value = "dataReact2", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public dataDemo dataReact2(@RequestBody String s) {
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("name", "张三");

//        System.out.println(RequestBody);
        JSONObject json = JSONObject.parseObject(s);
        log.info("接收参数:"+json);
//        System.out.println(json);
//        System.out.println(json.getString("Name"));

        data mysqldata = new data();
        dataDemo returnData = new dataDemo();
        returnData.setData(mysqldata.data1());

        returnData.setMsg("ok");
        returnData.setStatus(200);
        return returnData;
    }

    // 上传文件
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        File directory1 = new File("");
//        System.out.println(directory.getAbsoluteFile());
        Path base = Paths.get(directory1.getAbsolutePath());
//        System.out.println(base.resolve("Business\\csv\\"));


        String fileName = file.getOriginalFilename();

        Path path = base.resolve("Business" + File.separator + "csv");

//        File directory = new File(path.toString());
//        String directory = base.resolve("Business\\csv\\");
//        System.out.println(path.toString());

        // 创建目录
        DirUtils.createDir(path.toString());


        File dest = new File(path.toString() + File.separator + fileName);
        try {
            file.transferTo(dest);
//            LOGGER.info("上传成功");
            return "上传成功";
        } catch (IOException e) {
//            LOGGER.error(e.toString(), e);
            e.printStackTrace();
        }
        return "上传失败！";
    }

    // 下载
    @PostMapping("/download")
    @ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//        String fileName = "dalaoyang.jpeg";// 文件名
        File directory1 = new File("");
//        System.out.println(directory.getAbsoluteFile());
        Path base = Paths.get(directory1.getAbsolutePath());
//        System.out.println(base.resolve("Business\\csv\\"));


        String fileName = "端到端统一备份服务器台账20190816 (2).csv";

        Path path = base.resolve("Business" + File.separator + "csv");


        if (fileName != null) {
            //设置文件路径
            File file = new File(path.toString() + File.separator + fileName);
            //File file = new File(realPath , fileName);

            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }


}


class dataDemo {

    private List data;//测试名称.
    private String msg;
    private int status;

    public void setMsg(String data) {
        msg = data;
    }

    public void setStatus(int data) {
        status = data;
    }

    public List getData() {
        return data;
    }

    public void setData(List d) {
        data = d;
    }
}

